<template>
  <div @back="() => this.$router.go(-1)">
    <!-- 账户信息 start -->
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form-model
          layout="inline"
          :model="user"
          :rules="formRules"
          ref="formRef"
        >
          <a-descriptions :title="$t('all.autotext1137')" />
          <a-row>
            <a-col :span="4">
              <a-form-model-item :label="$t('all.autotext551')">
                <span>{{ user.account }}</span>
                <a v-copy="user.account" style="margin-left: 10px">{{ $t('all.autotext1285') }}</a>
              </a-form-model-item>
            </a-col>
            <a-col :span="10" v-if="user.pinCode">
              <a-form-model-item :label="$t('all.autotext902')">
                <span>{{ user.pinCode }}</span>
                <a v-copy="user.pinCode" style="margin-left: 10px">{{ $t('all.autotext1285') }}</a>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 头像 -->
          <a-row :gutter="48" :style="{'margin-bottom': '80px'}">
            <a-col :md="8" :sm="24">
              <a-form-model-item :label="$t('all.autotext1442')" prop="avatar">
                <a-avatar
                  v-if="isEdit && !imgUrl"
                  shape="square"
                  :size="64"
                  icon="user"
                />
                <a-upload
                  v-else
                  name="file"
                  :multiple="false"
                  action="/api/common/upload"
                  list-type="picture-card"
                  :headers="headers"
                  :file-list="fileList"
                  :show-upload-list="false"
                  :showUploadList="{showPreviewIcon:false}"
                  @change="handleChangeAvatar"
                >
                  <img
                    v-if="fileList.length < 1 && imgUrl"
                    :src="imgUrl"
                    :alt="$t('all.autotext618')"
                    style="width: 80px; height: 80px"
                  >
                </a-upload>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 用户名 -->
          <!-- <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item label="用户名" prop="userName">
                <span v-if="isEdit">{{ user.userName }} </span>
                <a-input v-else v-model="user.userName" :maxLength="20" />
              </a-form-model-item>
            </a-col>
          </a-row> -->
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item :label="$t('all.autotext44')" prop="email">
                <span v-if="isEdit">{{ user.email || $t('all.autotext1238') }} </span>
                <a-input
                  v-else
                  v-model="user.email"
                  :placeholder="$t('all.autotext1085')"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-model-item>
                <a v-if="user.email && !isEdit" @click="clickBindEmail()">{{ $t('all.autotext383') }}</a>
                <a v-if="!user.email && !isEdit" @click="clickBindEmail('bind')">{{ $t('all.autotext1270') }}</a>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 手机号 -->
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item :label="$t('all.autotext709')" prop="phone">
                <span v-if="isEdit">{{ user.phone | formatPhone() }} </span>
                <a-input v-else v-model="user.phone" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-model-item>
                <a v-if="!isEdit" @click="clickEditPhone">{{ $t('all.autotext1393') }}</a>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-descriptions :title="$t('all.autotext1287')" />
          <!-- 姓名 -->
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item :label="$t('all.autotext977')" prop="name">
                <span v-if="isEdit">{{ user.name }}</span>
                <a-input v-else v-model="user.name" :maxLength="10" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 生日 -->
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item :label="$t('all.autotext981')">
                <span v-if="isEdit">{{ user.birthday }}</span>
                <a-date-picker
                  v-else
                  v-model="user.birthday"
                  :disabled-date="disabledDate"
                  valueFormat="YYYY-MM-DD"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 证件类型 -->
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item :label="$t('all.autotext192')">
                <span v-if="isEdit">{{ user.cardType | enumValueByKey($const.DOCUMENT_TYPE) }}</span>
                <a-select v-else v-model="user.cardType" :disabled="user.verifiedStatus == 1">
                  <a-select-option v-for="(item, index) in $const.DOCUMENT_TYPE" :key="index" :value="item.value">
                    {{ item.desc }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 证件号码 -->
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-model-item :label="$t('all.autotext1359')" prop="idCard">
                <span v-if="isEdit">{{ user.idCard | formatIdCard() }}</span>
                <a-input v-else v-model="user.idCard" :disabled="user.verifiedStatus == 1" />
                <a v-if="user.verifiedStatus != 1" style="margin-left:15px" @click="handleAutuValid">{{ $t('all.autotext42') }}</a>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div class="table-operator" style="margin-top:35px">
          <a-button v-if="isEdit" type="primary" @click="clickEdit">{{ $t('all.autotext629') }}</a-button>
          <span v-else>
            <a-button type="primary" @click="clickSave">{{ $t('all.autotext321') }}</a-button>
            <a-button @click="clickCancel">{{ $t('all.autotext975') }}</a-button>
          </span>
          <a-button v-if="user.isAdmin == 0" type="danger" @click="clickDelete">{{ $t('all.autotext965') }}</a-button>
        </div>
      </div>
    </a-card>
    <!-- 账户信息 end -->
    <Modal
      :modalTitle="modalTitle"
      :modalVisible="modalVisible"
      :isPhone="isPhone"
      :phoneNumber="phoneNumber"
      @closeModal="closeModal"
    />
    <AuthModal :visible="authVisible" @handleCancel="handleAuthSuccess" :info="user" />
  </div>
</template>

<script>
import { getUserDetail, updateUser, cancellation } from '@/api/account/settings'
import { updatePersonDetail } from '@/api/account/person'
import moment from 'moment'
import Modal from './components/Modal.vue'
import AuthModal from './AuthModal'

export default {
  components: {
    Modal,
    AuthModal
  },
  data () {
    return {
      authVisible: false,
      hasImg: false,
      isEdit: true,
      imgUrl: '',
      isPhone: true, // 更改手机号和邮箱共用一个弹框，用于判断
      phoneNumber: null, // 点击绑定邮箱时将当前手机号传给子组件
      modalTitle: '',
      modalVisible: false,
      user: {},
      originUser: {},
      userCopy: {},
      headers: {
        authorization: 'authorization-text'
      },
      fileList: [], // 头像上传列表
      fileListCopy: [], // 头像上传列表
      formRules: {
        userName: [{ required: true, message: this.$t('all.autotext254'), trigger: 'change' }],
        name: [{ required: true, message: this.$t('all.autotext479'), trigger: 'change' }],
        // pwd: [{ required: true, message: '请输入密码', trigger: 'change' }],
        phone: [
          { required: true, message: this.$t('all.autotext396'), trigger: 'change' },
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: this.$t('all.autotext140') }
        ],
        idCard: [
          { required: false, message: this.$t('all.autotext1204'), trigger: 'change' },
          { trigger: 'blur', pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/, message: this.$t('all.autotext1052') }
        ],
        email: [
          { required: false },
          { pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: this.$t('all.autotext969') }
        ]
      }
    }
  },
  created () {
    this.getUserDetail(0)
  },
  methods: {
    clickDelete () {
      const that = this
      this.$confirm({
        title: this.$t('all.autotext730'),
        content: this.$t('all.autotext808'),
        onOk () {
          cancellation().then(res => {
            that.$message.success(that.$t('all.autotext1455'))
            that.$store.dispatch('Logout', 1).then(() => {
              that.$router.push({ name: 'login' })
            })
          })
        }
      })
    },
    // 获取个人信息
    // 注：传值的原因：有可能点击编辑后先修改了信息但未保存，接着修改邮箱或手机号此时应仅更新手机/邮箱，否则由于双向绑定，从接口获取的数据会替换掉用户输入但未保存的信息
    getUserDetail (val) {
      getUserDetail()
        .then(res => {
          if (!val) {
            this.user = res
            this.originUser = JSON.parse(JSON.stringify(res))
            if (res.headimg) {
              this.hasImg = true
              this.imgUrl = this.$minio + res.headimg
            } else {
              this.hasImg = false
              this.fileList = []
              this.imgUrl = ''
            }
          } else {
            this.user.phone = res.phone
            this.userCopy.phone = res.phone
            this.user.email = res.email
            this.userCopy.email = res.email
          }
          this.$store.commit('SET_AVATAR', res.headimg)
          this.$store.commit('SET_NAME', res.name)
          this.$globalVue.$emit('headUpdate')
        })
        .catch(() => {})
    },
    disabledDate (current) {
      return current > moment().endOf('day')
    },
    // 判断是否已有头像
    checkHasVantar (img) {
      if (img) {
        this.hasImg = true
        this.imgUrl = this.$options.filters.dealImageUrl(img) // 补全图片地址
      } else {
        this.hasImg = false
        this.fileList = []
        this.imgUrl = ''
      }
    },
    // 点击修改按钮修改信息
    clickEdit () {
      this.isEdit = !this.isEdit
      this.userCopy = { ...this.user }
      this.handleImg()
    },
    // 点击保存修改后的信息
    clickSave () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          // 走接口提交表单
          const { id, account, userName, name, email, phone, idCard, birthday, headimg } = { ...this.user }
          const commitData = { id, account, userName, name, email, phone, idCard, birthday, headimg }

          updateUser({ ...commitData })
            .then(res => {
              if (this.originUser.birthday !== birthday) {
                this.editBirthday()
              }
              if (this.originUser.idCard !== idCard) {
                this.editIdCard()
              }
              if (this.originUser.phone !== phone) {
                this.editPhone()
              }
              if (this.originUser.email !== email) {
                this.editEmail()
              }
              this.$message.success(this.$t('all.autotext181'))
              this.getUserDetail(0)
              this.isEdit = !this.isEdit
            })
            .catch(() => {})
        }
      })
    },
    // 点击取消修改信息
    clickCancel () {
      this.isEdit = !this.isEdit
      this.$refs.formRef.resetFields()
      this.user = this.userCopy
    },
    // 处理返回的图片
    handleImg () {
      // 判断是否为空 如果不为空则补全信息
      if (!this.user.headimg) {
        this.fileList = this.user.headimg.split(',').map(item => ({
          url: this.$options.filters.dealImageUrl(item), // 补全地址
          uid: item,
          name: item,
          status: 'done',
          response: {
            data: item
          }
        }))
      }
    },
    // 点击上传更改头像
    handleChangeAvatar ({ file, fileList }) {
      if (file.status === 'done') {
        const { response } = file
        if (response && response.status === '1' && response.data) {
          if (fileList.length === 1) {
            this.fileList = fileList
            this.dealImageStr(fileList)
          } else {
            this.fileList = []
          }
        } else {
          this.fileList = []
          this.$message.error(response && response.detail || this.$t('all.autotext1259'))
        }
      } else {
        this.fileList = fileList
      }
    },
    // 整理图片字符换传递给user
    dealImageStr (list) {
      this.user.headimg =
        list && list.length > 0
          ? list
            .map(item => {
              if (item.response) {
                return item.response.data
              }
            })
            .join()
          : ''
    },
    // 点击修改手机
    clickEditPhone () {
      this.modalVisible = true
      this.isPhone = true
      this.modalTitle = this.$t('all.autotext725')
    },
    // 点击绑定邮箱
    clickBindEmail (val) {
      this.phoneNumber = this.user.phone
      this.modalVisible = true
      this.isPhone = false
      if (val === 'bind') {
        this.modalTitle = this.$t('all.autotext1270')
      } else {
        this.modalTitle = this.$t('all.autotext757')
      }
    },
    // 关闭弹窗
    closeModal (val) {
      this.modalVisible = false
      // 邮箱绑定/更换 手机号更换后 需重新请求信息且将点击编辑时保存的个人信息副本中的电话和邮箱进行更改
      if (val) {
        this.getUserDetail(1)
      }
    },
    handleAutuValid () {
      const params = {
        name: this.user.name,
        idCard: this.user.idCard,
        birthday: this.user.birthday,
        phone: this.user.phone
      }
      updatePersonDetail(params).then(res => {
        if (res.status === true) {
          this.$notification.success({
            message: this.$t('all.autotext365')
          })
          this.getUserDetail(0)
        } else {
          this.$notification.error({
            message: this.$t('all.autotext40'),
            description: this.$t('all.autotext1002')
          })
        }
      })
    },
    handleAuthSuccess () {
      this.isEdit = true
      this.getUserDetail(0)
      this.handleCancelAuth()
    },
    handleCancelAuth (flag = false) {
      this.authVisible = flag
    },
    editBirthday () {},
    editIdCard () {},
    editPhone () {},
    editEmail () {}
  }
}
</script>

<style lang="less" scoped>
  .save-button {
    margin-right: 10px;
  }
</style>
